package com.wwf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wwf.mapper.IUserInfoMapper;
import com.wwf.mapper.IUserTokenMapper;
import com.wwf.pojo.UserInfo;
import com.wwf.pojo.UserToken;
import com.wwf.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wwf
 * @date 2021年02月04日 12:13:14
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    IUserInfoMapper userInfoMapper;
    @Autowired
    IUserTokenMapper userTokenMapper;
    @Override
    public int registerUser(UserInfo userInfo) {
        userInfo.setCreatetime(new Date());
        int id = userInfoMapper.insert(userInfo);
        return userInfo.getId();
    }

    @Override
    public boolean isRegister(String email) {
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail(email);
        QueryWrapper<UserInfo> userAuthCodeQuery = new QueryWrapper<UserInfo>(userInfo);
        List<UserInfo> userAuthCodes = userInfoMapper.selectList(userAuthCodeQuery);
        return userAuthCodes!=null && userAuthCodes.size()>0 ? true : false;
    }

    @Override
    public boolean checkLogin(String email, String password) {
        Map<String,Object> mapQuery = new HashMap<String,Object>();
        mapQuery.put("email",email);
        mapQuery.put("password",password);
        List<UserInfo> userInfos = userInfoMapper.selectByMap(mapQuery);
        if(userInfos !=null && userInfos.size()>0){
            return true;
        }
        return false;
    }

    @Override
    public void saveToken(String email, String accssToken) {
        UserToken userToken = new UserToken();
        userToken.setEmail(email);
        userToken.setToken(accssToken);
        userTokenMapper.insert(userToken);
    }

    @Override
    public UserToken findUserInfoBy(String accessToken) {
        Map<String,Object> mapQuery = new HashMap<String,Object>();
        mapQuery.put("token",accessToken);
        List<UserToken> userTokens = userTokenMapper.selectByMap(mapQuery);
        return userTokens != null && userTokens.size() >0?userTokens.get(0):null;
    }
}
